/**
 * 将毫秒，转换成时间字符串。例如说，xx 分钟
 *
 * @param ms 毫秒
 * @returns {string} 字符串
 */
export function getDate (ms) {
  const day = Math.floor(ms / (24 * 60 * 60 * 1000));
  const hour = Math.floor((ms / (60 * 60 * 1000) - day * 24));
  const minute = Math.floor(((ms / (60 * 1000)) - day * 24 * 60 - hour * 60));
  const second = Math.floor((ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60));
  if (day > 0) {
    return day + "天" + hour + "小时" + minute + "分钟";
  }
  if (hour > 0) {
    return hour + "小时" + minute + "分钟";
  }
  if (minute > 0) {
    return minute + "分钟";
  }
  if (second > 0) {
    return second + "秒";
  } else {
    return 0 + "秒";
  }
}

export function beginOfDay (date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

export function endOfDay (date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
}

//日期加上天数后的新日期.
export function addDays (date, days) {
  let nd = new Date(date);
  nd = nd.valueOf();
  nd = nd + days * 24 * 60 * 60 * 1000;
  nd = new Date(nd);
  //alert(nd.getFullYear() + "年" + (nd.getMonth() + 1) + "月" + nd.getDate() + "日");
  let y = nd.getFullYear();
  let m = nd.getMonth() + 1;
  let d = nd.getDate();
  if (m <= 9) m = "0" + m;
  if (d <= 9) d = "0" + d;
  let cdate = y + "-" + m + "-" + d;
  return cdate;
}

//日期1减去日期2的天数.
export function dateDiff (d1, d2) {
  const day = 24 * 60 * 60 * 1000;
  try {
    let dateArr = d1.split("-");
    let checkDate = new Date();
    checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
    let checkTime = checkDate.getTime();

    let dateArr2 = d2.split("-");
    let checkDate2 = new Date();
    checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
    let checkTime2 = checkDate2.getTime();

    let cha = (checkTime - checkTime2) / day;
    return cha;
  } catch (e) {
    return false;
  }
}